package com.lvyh.lightframe.multidatasource.aop;

import com.lvyh.lightframe.multidatasource.anotation.RouteDatasource;
import com.lvyh.lightframe.multidatasource.common.MultiDataSourceHolder;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author lvyh 2021/03/20.
 */
@Aspect
public class RouteDatasourceAspect {
    private static final Logger logger = LoggerFactory.getLogger(RouteDatasourceAspect.class);

    @Pointcut("@annotation(com.lvyh.lightframe.multidatasource.anotation.RouteDatasource)")
    public void point() {

    }

    @Before("point()&&@annotation(routeDatasource)")
    public void before(RouteDatasource routeDatasource) {
        if (MultiDataSourceHolder.getMultiDataSources().contains(routeDatasource.value())) {
            MultiDataSourceHolder.set(routeDatasource.value());
            logger.info("set current datasource :{}", routeDatasource.value());
        } else {
            MultiDataSourceHolder.set("master");
        }
    }

    @After("point()")
    public void after() {
        logger.info("clear current datasource :{}", MultiDataSourceHolder.get());
        MultiDataSourceHolder.remove();
    }
}
